<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>ArrayHelper - Helpers - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w130" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w130-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w130-collapse" class="collapse navbar-collapse"><ul id="w131" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w132" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-114" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-114" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-115" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-115" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item" href="#navigation-116" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-116" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-117" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-117" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-118" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-118" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-119" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-119" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-120" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-120" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-121" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-121" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-122" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-122" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-123" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-123" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-124" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-124" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-125" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-125" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-126" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-126" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-127" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-127" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-128" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-128" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item active" href="#navigation-129" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-129" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item active" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>ArrayHelper <span id="arrayhelper"></span><a href="#arrayhelper" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#getting-values">Getting Values</a></li>
<li><a href="#checking-existence-of-keys">Checking Existence of Keys</a></li>
<li><a href="#retrieving-columns">Retrieving Columns</a></li>
<li><a href="#reindexing-arrays">Re-indexing Arrays</a></li>
<li><a href="#building-maps">Building Maps</a></li>
<li><a href="#multidimensional-sorting">Multidimensional Sorting</a></li>
<li><a href="#detecting-array-types">Detecting Array Types</a></li>
<li><a href="#html-encoding-values">HTML Encoding and Decoding Values</a></li>
<li><a href="#merging-arrays">Merging Arrays</a></li>
<li><a href="#converting-objects-to-arrays">Converting Objects to Arrays</a></li>
<li><a href="#testing-arrays">Testing against Arrays</a></li></ol></div>
<p>Additionally to the <a href="http://php.net/manual/en/book.array.php">rich set of PHP array functions</a>, the Yii array helper provides
extra static methods allowing you to deal with arrays more efficiently.</p>
<h2>Getting Values  <span id="getting-values"></span><a href="#getting-values" class="hashlink">&para;</a></h2><p>Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite
repetitive. You have to check if key exists with <code>isset</code> first, then if it does you're getting it, if not,
providing default value:</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$name</span> = <span class="hljs-string">'Alex'</span>;
}

<span class="hljs-variable">$array</span> = [
    <span class="hljs-string">'foo'</span> =&gt; [
        <span class="hljs-string">'bar'</span> =&gt; <span class="hljs-keyword">new</span> User(),
    ]
];

<span class="hljs-variable">$value</span> = <span class="hljs-keyword">isset</span>(<span class="hljs-variable">$array</span>[<span class="hljs-string">'foo'</span>][<span class="hljs-string">'bar'</span>]-&gt;name) ? <span class="hljs-variable">$array</span>[<span class="hljs-string">'foo'</span>][<span class="hljs-string">'bar'</span>]-&gt;name : <span class="hljs-keyword">null</span>;
</code></pre>
<p>Yii provides a very convenient method to do it:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$value</span> = ArrayHelper::getValue(<span class="hljs-variable">$array</span>, <span class="hljs-string">'foo.bar.name'</span>);
</code></pre>
<p>First method argument is where we're getting value from. Second argument specifies how to get the data. It could be one
of the following:</p>
<ul>
<li>Name of array key or object property to retrieve value from.</li>
<li>Set of dot separated array keys or object property names. The one we've used in the example above.</li>
<li>A callback returning a value.</li>
</ul>
<p>The callback should be the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$fullName</span> = ArrayHelper::getValue(<span class="hljs-variable">$user</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$user</span>, <span class="hljs-variable">$defaultValue</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$user</span>-&gt;firstName . <span class="hljs-string">' '</span> . <span class="hljs-variable">$user</span>-&gt;lastName;
});
</code></pre>
<p>Third optional argument is default value which is <code>null</code> if not specified. Could be used as follows:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$username</span> = ArrayHelper::getValue(<span class="hljs-variable">$comment</span>, <span class="hljs-string">'user.username'</span>, <span class="hljs-string">'Unknown'</span>);
</code></pre>
<p>In case you want to get the value and then immediately remove it from array you can use <code>remove</code> method:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$array</span> = [<span class="hljs-string">'type'</span> =&gt; <span class="hljs-string">'A'</span>, <span class="hljs-string">'options'</span> =&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]];
<span class="hljs-variable">$type</span> = ArrayHelper::remove(<span class="hljs-variable">$array</span>, <span class="hljs-string">'type'</span>);
</code></pre>
<p>After executing the code <code>$array</code> will contain <code>['options' =&gt; [1, 2]]</code> and <code>$type</code> will be <code>A</code>. Note that unlike
<code>getValue</code> method, <code>remove</code> supports simple key names only.</p>
<h2>Checking Existence of Keys  <span id="checking-existence-of-keys"></span><a href="#checking-existence-of-keys" class="hashlink">&para;</a></h2><p><code>ArrayHelper::keyExists</code> works the same way as <a href="http://php.net/manual/en/function.array-key-exists.php">array_key_exists</a>
except that it also supports case-insensitive key comparison. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$data1</span> = [
    <span class="hljs-string">'userName'</span> =&gt; <span class="hljs-string">'Alex'</span>,
];

<span class="hljs-variable">$data2</span> = [
    <span class="hljs-string">'username'</span> =&gt; <span class="hljs-string">'Carsten'</span>,
];

<span class="hljs-keyword">if</span> (!ArrayHelper::keyExists(<span class="hljs-string">'username'</span>, <span class="hljs-variable">$data1</span>, <span class="hljs-keyword">false</span>) || !ArrayHelper::keyExists(<span class="hljs-string">'username'</span>, <span class="hljs-variable">$data2</span>, <span class="hljs-keyword">false</span>)) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"Please provide username."</span>;
}
</code></pre>
<h2>Retrieving Columns  <span id="retrieving-columns"></span><a href="#retrieving-columns" class="hashlink">&para;</a></h2><p>Often you need to get a column of values from array of data rows or objects. Common example is getting a list of IDs.</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$data</span> = [
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'abc'</span>],
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'def'</span>],
];
<span class="hljs-variable">$ids</span> = ArrayHelper::getColumn(<span class="hljs-variable">$array</span>, <span class="hljs-string">'id'</span>);
</code></pre>
<p>The result will be <code>['123', '345']</code>.</p>
<p>If additional transformations are required or the way of getting value is complex, second argument could be specified
as an anonymous function:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = ArrayHelper::getColumn(<span class="hljs-variable">$array</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$element</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$element</span>[<span class="hljs-string">'id'</span>];
});
</code></pre>
<h2>Re-indexing Arrays  <span id="reindexing-arrays"></span><a href="#reindexing-arrays" class="hashlink">&para;</a></h2><p>In order to index an array according to a specified key, the <code>index</code> method can be used. The input should be either
multidimensional array or an array of objects. The <code>$key</code> can be either a key name of the sub-array, a property name of
object, or an anonymous function that must return the value that will be used as a key.</p>
<p>The <code>$groups</code> attribute is an array of keys, that will be used to group the input array into one or more sub-arrays
based on keys specified.</p>
<p>If the <code>$key</code> attribute or its value for the particular element is null and <code>$groups</code> is not defined, the array
element will be discarded. Otherwise, if <code>$groups</code> is specified, array element will be added to the result array
without any key.</p>
<p>For example:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$array</span> = [
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'abc'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'laptop'</span>],
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'def'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'tablet'</span>],
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'hgi'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'smartphone'</span>],
];
<span class="hljs-variable">$result</span> = ArrayHelper::index(<span class="hljs-variable">$array</span>, <span class="hljs-string">'id'</span>);
</code></pre>
<p>The result will be an associative array, where the key is the value of <code>id</code> attribute</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-string">'123'</span> =&gt; [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'abc'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'laptop'</span>],
    <span class="hljs-string">'345'</span> =&gt; [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'hgi'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'smartphone'</span>]
    <span class="hljs-comment">// The second element of an original array is overwritten by the last element because of the same id</span>
]
</code></pre>
<p>Anonymous function, passed as a <code>$key</code>, gives the same result.</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = ArrayHelper::index(<span class="hljs-variable">$array</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$element</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$element</span>[<span class="hljs-string">'id'</span>];
});
</code></pre>
<p>Passing <code>id</code> as a third argument will group <code>$array</code> by <code>id</code>:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = ArrayHelper::index(<span class="hljs-variable">$array</span>, <span class="hljs-keyword">null</span>, <span class="hljs-string">'id'</span>);
</code></pre>
<p>The result will be a multidimensional array grouped by <code>id</code> on the first level and not indexed on the second level:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-string">'123'</span> =&gt; [
        [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'abc'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'laptop'</span>]
    ],
    <span class="hljs-string">'345'</span> =&gt; [ <span class="hljs-comment">// all elements with this index are present in the result array</span>
        [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'def'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'tablet'</span>],
        [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'hgi'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'smartphone'</span>],
    ]
]
</code></pre>
<p>An anonymous function can be used in the grouping array as well:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = ArrayHelper::index(<span class="hljs-variable">$array</span>, <span class="hljs-string">'data'</span>, [<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$element</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$element</span>[<span class="hljs-string">'id'</span>];
}, <span class="hljs-string">'device'</span>]);
</code></pre>
<p>The result will be a multidimensional array grouped by <code>id</code> on the first level, by <code>device</code> on the second level and
indexed by <code>data</code> on the third level:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-string">'123'</span> =&gt; [
        <span class="hljs-string">'laptop'</span> =&gt; [
            <span class="hljs-string">'abc'</span> =&gt; [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'abc'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'laptop'</span>]
        ]
    ],
    <span class="hljs-string">'345'</span> =&gt; [
        <span class="hljs-string">'tablet'</span> =&gt; [
            <span class="hljs-string">'def'</span> =&gt; [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'def'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'tablet'</span>]
        ],
        <span class="hljs-string">'smartphone'</span> =&gt; [
            <span class="hljs-string">'hgi'</span> =&gt; [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'data'</span> =&gt; <span class="hljs-string">'hgi'</span>, <span class="hljs-string">'device'</span> =&gt; <span class="hljs-string">'smartphone'</span>]
        ]
    ]
]
</code></pre>
<h2>Building Maps  <span id="building-maps"></span><a href="#building-maps" class="hashlink">&para;</a></h2><p>In order to build a map (key-value pairs) from a multidimensional array or an array of objects you can use <code>map</code> method.
The <code>$from</code> and <code>$to</code> parameters specify the key names or property names to set up the map. Optionally, one can further
group the map according to a grouping field <code>$group</code>. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$array</span> = [
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'123'</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'aaa'</span>, <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'x'</span>],
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'124'</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'bbb'</span>, <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'x'</span>],
    [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-string">'345'</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'ccc'</span>, <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'y'</span>],
);

<span class="hljs-variable">$result</span> = ArrayHelper::map(<span class="hljs-variable">$array</span>, <span class="hljs-string">'id'</span>, <span class="hljs-string">'name'</span>);
<span class="hljs-comment">// the result is:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//     '123' =&gt; 'aaa',</span>
<span class="hljs-comment">//     '124' =&gt; 'bbb',</span>
<span class="hljs-comment">//     '345' =&gt; 'ccc',</span>
<span class="hljs-comment">// ]</span>

<span class="hljs-variable">$result</span> = ArrayHelper::map(<span class="hljs-variable">$array</span>, <span class="hljs-string">'id'</span>, <span class="hljs-string">'name'</span>, <span class="hljs-string">'class'</span>);
<span class="hljs-comment">// the result is:</span>
<span class="hljs-comment">// [</span>
<span class="hljs-comment">//     'x' =&gt; [</span>
<span class="hljs-comment">//         '123' =&gt; 'aaa',</span>
<span class="hljs-comment">//         '124' =&gt; 'bbb',</span>
<span class="hljs-comment">//     ],</span>
<span class="hljs-comment">//     'y' =&gt; [</span>
<span class="hljs-comment">//         '345' =&gt; 'ccc',</span>
<span class="hljs-comment">//     ],</span>
<span class="hljs-comment">// ]</span>
</code></pre>
<h2>Multidimensional Sorting  <span id="multidimensional-sorting"></span><a href="#multidimensional-sorting" class="hashlink">&para;</a></h2><p><code>multisort</code> method helps to sort an array of objects or nested arrays by one or several keys. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$data</span> = [
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">30</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Alexander'</span>],
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">30</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Brian'</span>],
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">19</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Barney'</span>],
];
ArrayHelper::multisort(<span class="hljs-variable">$data</span>, [<span class="hljs-string">'age'</span>, <span class="hljs-string">'name'</span>], [SORT_ASC, SORT_DESC]);
</code></pre>
<p>After sorting we'll get the following in <code>$data</code>:</p>
<pre><code class="hljs php language-php">[
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">19</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Barney'</span>],
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">30</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Brian'</span>],
    [<span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">30</span>, <span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Alexander'</span>],
];
</code></pre>
<p>Second argument that specifies keys to sort by can be a string if it's a single key, an array in case of multiple keys
or an anonymous function like the following one:</p>
<pre><code class="hljs php language-php">ArrayHelper::multisort(<span class="hljs-variable">$data</span>, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(<span class="hljs-variable">$item</span>)</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">isset</span>(<span class="hljs-variable">$item</span>[<span class="hljs-string">'age'</span>]) ? [<span class="hljs-string">'age'</span>, <span class="hljs-string">'name'</span>] : <span class="hljs-string">'name'</span>;
});
</code></pre>
<p>Third argument is direction. In case of sorting by a single key it could be either <code>SORT_ASC</code> or
<code>SORT_DESC</code>. If sorting by multiple values you can sort each value differently by providing an array of
sort direction.</p>
<p>Last argument is PHP sort flag that could take the same values as the ones passed to
PHP <a href="http://php.net/manual/en/function.sort.php">sort()</a>.</p>
<h2>Detecting Array Types  <span id="detecting-array-types"></span><a href="#detecting-array-types" class="hashlink">&para;</a></h2><p>It is handy to know whether an array is indexed or an associative. Here's an example:</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// no keys specified</span>
<span class="hljs-variable">$indexed</span> = [<span class="hljs-string">'Qiang'</span>, <span class="hljs-string">'Paul'</span>];
<span class="hljs-keyword">echo</span> ArrayHelper::isIndexed(<span class="hljs-variable">$indexed</span>);

<span class="hljs-comment">// all keys are strings</span>
<span class="hljs-variable">$associative</span> = [<span class="hljs-string">'framework'</span> =&gt; <span class="hljs-string">'Yii'</span>, <span class="hljs-string">'version'</span> =&gt; <span class="hljs-string">'2.0'</span>];
<span class="hljs-keyword">echo</span> ArrayHelper::isAssociative(<span class="hljs-variable">$associative</span>);
</code></pre>
<h2>HTML Encoding and Decoding Values  <span id="html-encoding-values"></span><a href="#html-encoding-values" class="hashlink">&para;</a></h2><p>In order to encode or decode special characters in an array of strings into HTML entities you can use the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$encoded</span> = ArrayHelper::htmlEncode(<span class="hljs-variable">$data</span>);
<span class="hljs-variable">$decoded</span> = ArrayHelper::htmlDecode(<span class="hljs-variable">$data</span>);
</code></pre>
<p>Only values will be encoded by default. By passing second argument as <code>false</code> you can encode array's keys as well.
Encoding will use application charset and could be changed via third argument.</p>
<h2>Merging Arrays  <span id="merging-arrays"></span><a href="#merging-arrays" class="hashlink">&para;</a></h2><pre><code class="hljs php language-php">  <span class="hljs-comment">/**
    * Merges two or more arrays into one recursively.
    * If each array has an element with the same string key value, the latter
    * will overwrite the former (different from array_merge_recursive).
    * Recursive merging will be conducted if both arrays have an element of array
    * type and are having the same key.
    * For integer-keyed elements, the elements from the latter array will
    * be appended to the former array.
    * <span class="hljs-doctag">@param</span> array $a array to be merged to
    * <span class="hljs-doctag">@param</span> array $b array to be merged from. You can specify additional
    * arrays via third argument, fourth argument etc.
    * <span class="hljs-doctag">@return</span> array the merged array (the original arrays are not changed.)
    */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">merge</span><span class="hljs-params">(<span class="hljs-variable">$a</span>, <span class="hljs-variable">$b</span>)</span>
</span></code></pre>
<h2>Converting Objects to Arrays  <span id="converting-objects-to-arrays"></span><a href="#converting-objects-to-arrays" class="hashlink">&para;</a></h2><p>Often you need to convert an object or an array of objects into an array. The most common case is converting active record
models in order to serve data arrays via REST API or use it otherwise. The following code could be used to do it:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$posts</span> = Post::find()-&gt;limit(<span class="hljs-number">10</span>)-&gt;all();
<span class="hljs-variable">$data</span> = ArrayHelper::toArray(<span class="hljs-variable">$posts</span>, [
    <span class="hljs-string">'app\models\Post'</span> =&gt; [
        <span class="hljs-string">'id'</span>,
        <span class="hljs-string">'title'</span>,
        <span class="hljs-comment">// the key name in array result =&gt; property name</span>
        <span class="hljs-string">'createTime'</span> =&gt; <span class="hljs-string">'created_at'</span>,
        <span class="hljs-comment">// the key name in array result =&gt; anonymous function</span>
        <span class="hljs-string">'length'</span> =&gt; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$post</span>)</span> </span>{
            <span class="hljs-keyword">return</span> strlen(<span class="hljs-variable">$post</span>-&gt;content);
        },
    ],
]);
</code></pre>
<p>The first argument contains the data we want to convert. In our case we're converting a <code>Post</code> AR model.</p>
<p>The second argument is conversion mapping per class. We're setting a mapping for <code>Post</code> model.
Each mapping array contains a set of mappings. Each mapping could be:</p>
<ul>
<li>A field name to include as is.</li>
<li>A key-value pair of desired array key name and model column name to take value from.</li>
<li>A key-value pair of desired array key name and a callback which returns value.</li>
</ul>
<p>The result of conversion above will be:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-string">'id'</span> =&gt; <span class="hljs-number">123</span>,
    <span class="hljs-string">'title'</span> =&gt; <span class="hljs-string">'test'</span>,
    <span class="hljs-string">'createTime'</span> =&gt; <span class="hljs-string">'2013-01-01 12:00AM'</span>,
    <span class="hljs-string">'length'</span> =&gt; <span class="hljs-number">301</span>,
]
</code></pre>
<p>It is possible to provide default way of converting object to array for a specific class by implementing
<a href="./yii-base-arrayable.html">Arrayable</a> interface in that class.</p>
<h2>Testing against Arrays  <span id="testing-arrays"></span><a href="#testing-arrays" class="hashlink">&para;</a></h2><p>Often you need to check if an element is in an array or a set of elements is a subset of another.
While PHP offers <code>in_array()</code>, this does not support subsets or <code>\Traversable</code> objects.</p>
<p>To aid these kinds of tests, <a href="./yii-helpers-arrayhelper.html">yii\helpers\ArrayHelper</a> provides <a href="./yii-helpers-basearrayhelper.html#isIn()-detail">isIn()</a>
and <a href="./yii-helpers-basearrayhelper.html#isSubset()-detail">isSubset()</a> with the same signature as
<a href="http://php.net/manual/en/function.in-array.php">in_array()</a>.</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// true</span>
ArrayHelper::isIn(<span class="hljs-string">'a'</span>, [<span class="hljs-string">'a'</span>]);
<span class="hljs-comment">// true</span>
ArrayHelper::isIn(<span class="hljs-string">'a'</span>, <span class="hljs-keyword">new</span>(ArrayObject[<span class="hljs-string">'a'</span>]));

<span class="hljs-comment">// true </span>
ArrayHelper::isSubset(<span class="hljs-keyword">new</span>(ArrayObject[<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>]), <span class="hljs-keyword">new</span>(ArrayObject[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>])

</code></pre>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:28 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
